package com.pengheng.pojo;

import com.pengheng.enums.ResultCode;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

/**
 * ResultVo 为响应对象
 *
 * @author pengheng
 */
@Data
@NoArgsConstructor
public class ResultVo<T> implements Serializable {

    private static final long serialVersionUID = -7535228184843182772L;

    /**
     * 返回的code
     */
    private String code;

    /**
     * 返回的信息
     */
    private String msg;

    /**
     * 返回的结果集合
     */
    private T data;

    /**
     * 返回时间戳信息
     */
    private String timestamp = String.valueOf(System.currentTimeMillis());

    /**
     * 返回时间 “yyyy-MM-dd HH:mm:ss”格式
     */
    private String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(this.timestamp)));

    private ResultVo(String code, String message) {
        this(code, message, null);
    }

    private ResultVo(String code, String message, T data) {
        this.code = Optional.ofNullable(code).orElse("");
        this.msg = Optional.ofNullable(message).orElse("");
        this.data = data;

    }

    public static <Result> ResultVo<Result> success(Result result) {
        return new ResultVo<>(ResultCode.SUCCESS.getCode(), "获取数据成功", result);
    }

    public static ResultVo<Void> success(String message) {
        return new ResultVo<>(ResultCode.SUCCESS.getCode(), message);
    }

    public static <Result> ResultVo<Result> success(String message, Result result) {
        return new ResultVo<>(ResultCode.SUCCESS.getCode(), message, result);
    }

    public static <Result> ResultVo<Result> error(String message) {
        return new ResultVo<>(ResultCode.ERROR.getCode(), message);
    }

    public static ResultVo<Void> error(ResultCode resultCode) {
        return new ResultVo<>(resultCode.getCode(), resultCode.getMessage());
    }

    public static ResultVo<Void> error(String code, String message) {
        return new ResultVo<>(code, message);
    }

    public static <Result> ResultVo<Result> error(ResultCode code, Result result) {
        return new ResultVo<>(code.getCode(), code.getMessage(), result);
    }

    public static <Result> ResultVo<Result> error(ResultCode code,String message, Result result) {
        return new ResultVo<>(code.getCode(), message, result);
    }

    public static <Result> boolean isNullOrFailCode(ResultVo<Result> resultVo) {
        return null == resultVo || !ResultCode.SUCCESS.getCode().equals(resultVo.getCode());
    }

}